#!/bin/bash
set -ex

TAR_VERSION="focal"
BASE_URL="http://mirrors.ustc.edu.cn/ubuntu-cloud-images/${TAR_VERSION}/current/${TAR_VERSION}-server-cloudimg-amd64-wsl.rootfs.tar.gz"
TAR_NAME=rootfs.ubuntu.tar.gz


einfo() {
	printf '\n\033[1;36m> %s\033[0m\n' "$@" >&2  # bold cyan
}

make_rootfs(){
    einfo 'Make rootfs...'
    if [ ! -d rootfs ];then
        mkdir rootfs
    fi
    rm -rf rootfs/*
    FILE_NAME=${BASE_URL##*/}
    if [ ! -s ${FILE_NAME} ];then
        curl -fLO $BASE_URL
    fi
    tar -zxpf *.tar.gz -C rootfs
}

prepare_chroot(){
    einfo 'Prepare chroot...'
    cp -rf content/* rootfs/
    rm -f "rootfs/etc/resolv.conf"
    cat > "rootfs/etc/resolv.conf" <<'EOF'
nameserver 8.8.8.8
nameserver 77.88.8.8
nameserver 8.8.4.4
nameserver 77.88.8.1
EOF
    # cp -f /etc/resolv.conf rootfs/etc/resolv.conf
}

install_chroot(){
    einfo 'Installing chroot...'
    cp chroot rootfs/chroot
    chmod +x rootfs/chroot
    chroot rootfs /bin/bash -c "sh chroot"
    rm rootfs/chroot
}

archive_rootfs(){
    einfo 'Creating rootfs archive...'
    if [ ! -d tars ];then
        mkdir tars
    fi
    cd rootfs;
    tar -zcpf ../tars/$TAR_NAME `ls`
    cd ..;
    chown `id -un` tars/$TAR_NAME
}

clean_up(){
    einfo 'Clear Up...'
    rm -rf rootfs
    # rm *.tar.gz
}

make_rootfs
prepare_chroot
install_chroot
archive_rootfs
clean_up